﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyShowBinTree
{
    public class MinHeap
    {
        public int[] Arr {
            get;
            set;
        }

        public MinHeap(int[] arr) {
            this.Arr = arr;
            this.buildHeap();
        }

        private void buildHeap()
        {
            int len = this.Arr.Count();
            int start = len / 2 - 1;
            for (int i = start; i>=0; i--)
            {
                heapfly(i);
            }
        }

        /// <summary>
        /// 调整堆
        /// </summary>
        /// <param name="index"></param>
        private void heapfly(int index) {
            int leftIndex = index * 2 + 1;
            int rightIndex = index * 2 + 2;
            int minIndex = index;

            if (leftIndex < this.Arr.Count() && this.Arr[leftIndex] < this.Arr[index]) {
                minIndex = leftIndex;
            }

            if (rightIndex < this.Arr.Count() && this.Arr[rightIndex] < this.Arr[minIndex]) {
                minIndex = rightIndex;
            }

            if (minIndex == index) {
                return;
            }
            swap(minIndex,index);
            heapfly(minIndex);
        }

        private void swap(int minIndex, int index)
        {
            int tem = this.Arr[minIndex];
            this.Arr[minIndex] = this.Arr[index];
            this.Arr[index] = tem;
        }

        public Image getImage()
        {
            TreeNode root = new TreeNode(Arr[0]);
            root.left = GetTreeNode(1);
            root.right = GetTreeNode(2);
            Image img = Common.GetTreeImage(root);
            return img;
        }

        private TreeNode GetTreeNode(int index)
        {
            if (index >= Arr.Length) {
                return null;
            }
            TreeNode node = new TreeNode(Arr[index]);
            node.left = GetTreeNode(index * 2 + 1);
            node.right = GetTreeNode(index * 2 + 2);
            return node;
        }




    }
}
